const fs = require("fs");
const path = require("path");
const vm = require("vm");
function Module(id) {
  this.id = id;
  this.exports = {};
}
Module._resovleFilename = function (filename) {
  let absPath = path.resolve(__dirname, filename);
  console.log(absPath);
  if (fs.existsSync(absPath)) {
    return absPath;
  } else {
    let suffix = Object.keys(Module._extensions);
    console.log(suffix);
    for (let i = 0; i < suffix.length; i++) {
      let newPath = absPath + suffix[i];
      if (fs.existsSync(newPath)) {
        return newPath;
      }
    }
  }
  throw new Error(`${filename} is not exists`);
};
Module._extensions = {
  ".js"(module) {
    let content = fs.readFileSync(module.id, "utf-8");
    content = Module.wrapper[0] + content + Module.wrapper[1];
    console.log(content);
    let compileFn = vm.runInThisContext(content);
    console.log(compileFn, "obj");
    let exports = module.exports;
    let dirname = path.dirname(module.id);
    let filename = module.id;
    compileFn.call(exports, exports, myReq, module, filename, dirname);
  },
  ".json"(module) {
    let content = JSON.parse(fs.readFileSync(module.id, "utf-8"));
    module.exports = content;
  },
};
Module._cache = {};
Module.wrapper = [
  "(function (exports,require,module,_filename,_dirname) {",
  " })",
];
Module.prototype.load = function () {
  let extname = path.extname(this.id);
  Module._extensions[extname](this);
};
function myReq(filename) {
  let mPath = Module._resovleFilename(filename);
  console.log(mPath);
  let cacheModule = Module._cache[mPath];
  if (cacheModule) return cacheModule.exports;
  let module = new Module(mPath);
  Module._cache[mPath] = module;
  module.load();
  return module.exports;
}

let obj = myReq("./text");
console.log(obj, "as");
